<template>
  <div class="search-page">
    <!-- 搜索栏 -->
    <van-search
      v-model="searchValue"
      placeholder="搜索维权案例、模板"
      show-action
      @search="onSearch"
      @cancel="$router.back()"
      autofocus
    />

    <!-- 搜索历史 -->
    <div v-if="!searchValue && searchHistory.length > 0" class="search-history">
      <div class="section-header">
        <span class="section-title">搜索历史</span>
        <van-icon name="delete-o" @click="clearHistory" />
      </div>
      <div class="history-tags">
        <van-tag
          v-for="item in searchHistory"
          :key="item"
          type="default"
          @click="searchValue = item; onSearch()"
        >
          {{ item }}
        </van-tag>
      </div>
    </div>

    <!-- 热门搜索 -->
    <div v-if="!searchValue" class="hot-search">
      <div class="section-title">热门搜索</div>
      <div class="hot-tags">
        <van-tag
          v-for="item in hotSearches"
          :key="item"
          type="primary"
          @click="searchValue = item; onSearch()"
        >
          {{ item }}
        </van-tag>
      </div>
    </div>

    <!-- 搜索结果 -->
    <div v-if="searchValue && searchResults.length > 0" class="search-results">
      <div class="result-tabs">
        <div
          v-for="tab in resultTabs"
          :key="tab.key"
          class="tab-item"
          :class="{ active: activeTab === tab.key }"
          @click="activeTab = tab.key"
        >
          {{ tab.name }} ({{ tab.count }})
        </div>
      </div>

      <div class="result-list">
        <div
          v-for="item in filteredResults"
          :key="item.id"
          class="result-item"
          @click="goToDetail(item)"
        >
          <div class="result-type">{{ getTypeText(item.type) }}</div>
          <div class="result-title">{{ highlightKeyword(item.title) }}</div>
          <div class="result-content">{{ highlightKeyword(item.content) }}</div>
          <div class="result-meta">
            <span class="result-time">{{ item.time }}</span>
            <span v-if="item.category" class="result-category">{{ item.category }}</span>
          </div>
        </div>
      </div>
    </div>

    <!-- 无搜索结果 -->
    <div v-if="searchValue && searchResults.length === 0 && !loading" class="no-results">
      <van-empty description="暂无搜索结果" />
      <div class="suggestions">
        <div class="suggestion-title">搜索建议：</div>
        <ul class="suggestion-list">
          <li>检查输入的关键词是否正确</li>
          <li>尝试使用更简单的关键词</li>
          <li>尝试使用同义词或相关词汇</li>
        </ul>
      </div>
    </div>

    <!-- 加载状态 -->
    <van-loading v-if="loading" class="loading-center" />
  </div>
</template>

<script setup>
import { ref, computed, onMounted } from 'vue'
import { useRouter } from 'vue-router'

const router = useRouter()

// 响应式数据
const searchValue = ref('')
const loading = ref(false)
const activeTab = ref('all')
const searchResults = ref([])
const searchHistory = ref([])

// 热门搜索
const hotSearches = ref([
  '工资拖欠', '押金不退', '商品质量', '劳动仲裁',
  '消费维权', '租房纠纷', '合同违约', '法律援助'
])

// 结果分类
const resultTabs = ref([
  { key: 'all', name: '全部', count: 0 },
  { key: 'post', name: '帖子', count: 0 },
  { key: 'template', name: '模板', count: 0 },
  { key: 'case', name: '案例', count: 0 }
])

// 模拟搜索结果数据
const mockResults = [
  {
    id: 1,
    type: 'post',
    title: '公司拖欠工资3个月，该怎么办？',
    content: '我在一家小公司工作，已经3个月没发工资了，老板总是找各种理由推脱...',
    category: '职场纠纷',
    time: '2天前'
  },
  {
    id: 2,
    type: 'template',
    title: '劳动仲裁申请书模板',
    content: '适用于工资拖欠、违法解除劳动合同等劳动争议案件的仲裁申请...',
    category: '职场纠纷',
    time: '1周前'
  },
  {
    id: 3,
    type: 'case',
    title: '成功追回拖欠工资案例分享',
    content: '通过劳动仲裁，我成功追回了被拖欠的3个月工资和经济补偿金...',
    category: '职场纠纷',
    time: '1个月前'
  }
]

// 计算属性
const filteredResults = computed(() => {
  if (activeTab.value === 'all') {
    return searchResults.value
  }
  return searchResults.value.filter(item => item.type === activeTab.value)
})

// 方法
const onSearch = async () => {
  if (!searchValue.value.trim()) return
  
  loading.value = true
  
  // 添加到搜索历史
  if (!searchHistory.value.includes(searchValue.value)) {
    searchHistory.value.unshift(searchValue.value)
    if (searchHistory.value.length > 10) {
      searchHistory.value = searchHistory.value.slice(0, 10)
    }
    localStorage.setItem('searchHistory', JSON.stringify(searchHistory.value))
  }
  
  // 模拟搜索API
  await new Promise(resolve => setTimeout(resolve, 1000))
  
  // 模拟搜索结果
  const keyword = searchValue.value.toLowerCase()
  searchResults.value = mockResults.filter(item =>
    item.title.toLowerCase().includes(keyword) ||
    item.content.toLowerCase().includes(keyword)
  )
  
  // 更新分类计数
  updateTabCounts()
  
  loading.value = false
}

const updateTabCounts = () => {
  resultTabs.value[0].count = searchResults.value.length
  resultTabs.value[1].count = searchResults.value.filter(item => item.type === 'post').length
  resultTabs.value[2].count = searchResults.value.filter(item => item.type === 'template').length
  resultTabs.value[3].count = searchResults.value.filter(item => item.type === 'case').length
}

const clearHistory = () => {
  searchHistory.value = []
  localStorage.removeItem('searchHistory')
}

const getTypeText = (type) => {
  const typeMap = {
    post: '帖子',
    template: '模板',
    case: '案例'
  }
  return typeMap[type] || '未知'
}

const highlightKeyword = (text) => {
  if (!searchValue.value) return text
  const keyword = searchValue.value
  const regex = new RegExp(`(${keyword})`, 'gi')
  return text.replace(regex, '<mark>$1</mark>')
}

const goToDetail = (item) => {
  const routeMap = {
    post: `/community/post/${item.id}`,
    template: `/templates/${item.id}`,
    case: `/community/post/${item.id}`
  }
  router.push(routeMap[item.type] || '/')
}

onMounted(() => {
  // 加载搜索历史
  const history = localStorage.getItem('searchHistory')
  if (history) {
    searchHistory.value = JSON.parse(history)
  }
  
  // 获取URL参数中的搜索词
  const urlParams = new URLSearchParams(window.location.search)
  const q = urlParams.get('q')
  if (q) {
    searchValue.value = q
    onSearch()
  }
})
</script>

<style scoped>
.search-page {
  min-height: 100vh;
  background: #f7f8fa;
}

.search-history, .hot-search {
  background: white;
  padding: 16px;
  margin-bottom: 8px;
}

.section-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 12px;
}

.section-title {
  font-size: 14px;
  font-weight: 600;
  color: #323233;
}

.history-tags, .hot-tags {
  display: flex;
  flex-wrap: wrap;
  gap: 8px;
}

.history-tags .van-tag,
.hot-tags .van-tag {
  cursor: pointer;
}

.search-results {
  background: white;
}

.result-tabs {
  display: flex;
  border-bottom: 1px solid #eee;
}

.tab-item {
  flex: 1;
  text-align: center;
  padding: 12px;
  font-size: 14px;
  color: #646566;
  cursor: pointer;
  border-bottom: 2px solid transparent;
}

.tab-item.active {
  color: #1989fa;
  border-bottom-color: #1989fa;
}

.result-list {
  padding: 8px 0;
}

.result-item {
  padding: 16px;
  border-bottom: 1px solid #f0f0f0;
  cursor: pointer;
}

.result-item:hover {
  background: #f7f8fa;
}

.result-type {
  font-size: 12px;
  color: #1989fa;
  background: #f0f9ff;
  padding: 2px 6px;
  border-radius: 3px;
  display: inline-block;
  margin-bottom: 8px;
}

.result-title {
  font-size: 16px;
  font-weight: 600;
  color: #323233;
  margin-bottom: 8px;
  line-height: 1.4;
}

.result-content {
  font-size: 14px;
  color: #646566;
  line-height: 1.5;
  margin-bottom: 12px;
  display: -webkit-box;
  -webkit-line-clamp: 2;
  -webkit-box-orient: vertical;
  overflow: hidden;
}

.result-meta {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.result-time {
  font-size: 12px;
  color: #969799;
}

.result-category {
  font-size: 12px;
  color: #1989fa;
  background: #f0f9ff;
  padding: 2px 6px;
  border-radius: 3px;
}

.no-results {
  padding: 40px 16px;
  text-align: center;
}

.suggestions {
  margin-top: 24px;
  text-align: left;
}

.suggestion-title {
  font-size: 14px;
  font-weight: 600;
  color: #323233;
  margin-bottom: 8px;
}

.suggestion-list {
  font-size: 13px;
  color: #646566;
  line-height: 1.6;
  padding-left: 16px;
}

.loading-center {
  position: fixed;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
}

:deep(mark) {
  background: #fff2cc;
  color: #d46b08;
  padding: 0 2px;
}
</style>